package com.wlxk.crawler.core.enums;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.wlxk.crawler.core.exception.WlxkErrEnum;
import com.wlxk.crawler.core.exception.WlxkException;
import com.wlxk.crawler.core.manager.qishuta.QishutaPageProcessor;
import com.wlxk.crawler.core.manager.siluke.SilukePageProcessor;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @description:
 * @author: 21054523
 * @time: 2023/11/2 10:45
 */
public enum SourceEnum {
    SILUKE("siluke", "m.siluke.com", "silukePipeline", SilukePageProcessor.class),
    QISHUTA("qishuta", "m.qishuta.org", "qishutaPipeline", QishutaPageProcessor.class);

    public final String key;
    public final String host;
    public final String pipeline;
    public final Class clazz;

    SourceEnum(String key, String host, String pipeline, Class clazz) {
        this.key = key;
        this.host = host;
        this.pipeline = pipeline;
        this.clazz = clazz;
    }

    public static SourceEnum getByKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        for (SourceEnum item : SourceEnum.values()) {
            if (item.key.equals(key)) {
                return item;
            }
        }
        return null;
    }

    public static SourceEnum getByUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        return getByHost(URLUtil.url(url).getHost());
    }

    public static SourceEnum getByHost(String host) {
        if (StringUtils.isEmpty(host)) {
            return null;
        }
        for (SourceEnum item : SourceEnum.values()) {
            if (item.host.equals(host)) {
                return item;
            }
        }
        return null;
    }

    public PageProcessor getPageProcessor() {
        try {
            return (PageProcessor) this.clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new WlxkException(WlxkErrEnum.UNKNOWN);
        }
    }

    public Pipeline getPipelineBean() {
        return SpringUtil.getBean(this.pipeline);
    }

}
